<?php
/**
 * Created by PhpStorm.
 * User:
 * Date:
 * Time:
 */

namespace ethink\mvc;


use ethink\misc\ErrorDescriptions;
use ethink\net\Url;
use think\Config;
use think\Controller;
use think\Exception;
use think\Request;
use think\Response;

class BaseController extends Controller
{
    protected $auth;
    protected $beforeActionList = ['beforeAction1'];
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $reqOrigin = isset($_SERVER['HTTP_ORIGIN'])?$_SERVER['HTTP_ORIGIN']:'';
        $configOrigin = Config::get('common')['allowOrigin'];
        if(in_array($reqOrigin,$configOrigin)){
            header("Access-Control-Allow-Credentials:true");
            header("Access-Control-Allow-Headers:Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild");
            header("Access-Control-Allow-Methods:PUT, POST, GET, DELETE, OPTIONS");
            header("Access-Control-Allow-Origin:$reqOrigin"); 
        }
    }
    /**
     * [beforeAction1 description]
     * @return [type] [description]
     */
    public function beforeAction1(){
    }

    /**
     * [检测用户状态]
     * @return [type] [description]
     */
    public function checkUserStatus(){
        trace("checkUserStatus");
        $data = $this->auth->getData();
        // var_dump($data);exit;
        if($data){
            $ret['status'] = 0;
            $ret['session'] = $data;
        }
        else{
            $ret['status'] = 2003;
        }
        return $ret;        
    }

    /**
     * [获取配置信息]
     * @param  [type] $param [description]
     * @return [type]        [description]
     */
    public function getConfig($param){
        $app = new \think\App(); 
        $config = $app::initCommon();
        return $config[$param];
    }
    /**
     * [getJsonData description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    protected function getJsonData($params)
    {
        if (isset($params) && !is_array($params)) {
            trace("Invalid params type, not array", 'error');
            return 1000;
        }
        $body = Request::instance()->getContent();
        if ($body) {
            $bodyArr = null;
            try {
                $bodyArr = json_decode($body, true);
                if (is_null($bodyArr)) {
                    trace("decode json body error\n body: $body\n error message: ". json_last_error_msg(), 'error');
                    return 1001;
                }
                if ($params) {
                    foreach ($params as $key) {
                        if (!isset($bodyArr[$key])) {
                            trace("Missing parameter: $key", 'error');
                            return 1002;
                        }
                    }
                }
                return $bodyArr;
            } catch (Exception $e) {
                trace("decode json body error, Exception: " . $e->getMessage(), 'error');
                return 1001;
            }
        } else {
            return 1003;
        }
    }
    /**
     * [responseJson description]
     * @param  [type]  $data   [description]
     * @param  integer $status [description]
     * @return [type]          [description]
     */
    public function responseJson($data = null, $status = 0){
        $content = null;
        if(is_array($data) || is_null($data)){
            $respArr = Array(
                "status" => $status,
                "desc" => ErrorDescriptions::getErrorDesc($status)
            );
            if($data){
                $respArr = array_merge($respArr, $data);
            }
            trace("response success data:".json_encode($respArr, 200));
            return json($respArr, 200);
        }else{
            trace("response unknown data type", 'error');
            return Response::create()->code(500);
        }
    }
    /**
     * [redirect description]
     * @param  [type]  $url    [description]
     * @param  array   $params [description]
     * @param  integer $code   [description]
     * @param  array   $with   [description]
     * @return [type]          [description]
     */
    public function redirect($url, $params = [], $code = 302, $with = [])
    {
        trace("-----:".$url);
        Url::root(Config::get('common.url_root'));
        parent::redirect($url, $params, $code, $with);
    }
    /**
     * [buildFullUrl description]
     * @param  string  $url    [description]
     * @param  string  $vars   [description]
     * @param  boolean $suffix [description]
     * @param  boolean $domain [description]
     * @return [type]          [description]
     */
    public function buildFullUrl($url = '', $vars = '', $suffix = true, $domain = false)
    {
        Url::root(Config::get('common.url_root'));
        return  $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER["SERVER_NAME"]. ':'.$_SERVER["SERVER_PORT"]
            . Url::build($url, $vars, $suffix, $domain);
    }

    /**
     * 保存头像到本地
     * 用于第三方帐号登录，获取头像
     */
    public function downloadUrl($url)
    {
        // $datenow = date("Ymd");
        // $path = $this->createpath($datenow);
        // $saveName = $this->createname();
        // // 移动
        // $this->getImage($url,$path,$saveName);
        // $desurls = Config::get('common.url_root') . 'uploads/'.$datenow.'/'. $saveName;
        // return $desurls;
    }

    /**
     * [createpath description]
     * @param  [type] $datenow [description]
     * @return [type]          [description]
     */
    public function createpath($datenow){
        $path = ROOT_PATH . 'public/uploads/'.$datenow;
        // 检测目录
        if (!is_dir($path)) {
            mkdir($path, 0755, true);
        }
        return $path;
    }
    /**
     * [createname description]
     * @return [type] [description]
     */
    public function createname(){
        return date("YmdHis").rand(10000,99999);
    }

    /**
     * 功能：php完美实现下载远程图片保存到本地
     * 参数：文件url,保存文件目录,保存文件名称，使用的下载方式
     * 当保存文件名称为空时则使用远程文件原来的名称
     * @param $url
     * @param string $save_dir
     * @param string $filename
     * @param int $type
     * @return array
     */
    private function getImage($url,$save_dir='',$filename='',$type=0){
        if(trim($url)==''){
            return array('file_name'=>'','save_path'=>'','error'=>1);
        }
        if(trim($save_dir)==''){
            $save_dir='./';
        }
        if(trim($filename)==''){//保存文件名
            $ext=strrchr($url,'.');
            if($ext!='.gif'&&$ext!='.jpg'){
                return array('file_name'=>'','save_path'=>'','error'=>3);
            }
            $filename=time().$ext;
        }
        if(0!==strrpos($save_dir,'/')){
            $save_dir.='/';
        }
        //创建保存目录
        if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){
            return array('file_name'=>'','save_path'=>'','error'=>5);
        }
        //获取远程文件所采用的方法
        if($type){
            $ch=curl_init();
            $timeout=5;
            curl_setopt($ch,CURLOPT_URL,$url);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
            curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
            $img=curl_exec($ch);
            curl_close($ch);
        }else{
            ob_start();
            readfile($url);
            $img=ob_get_contents();
            ob_end_clean();
        }
        //$size=strlen($img);
        //文件大小
        $fp2=@fopen($save_dir.$filename,'a');
        fwrite($fp2,$img);
        fclose($fp2);
        unset($img,$url);
        return array('file_name'=>$filename,'save_path'=>$save_dir.$filename,'error'=>0);
    }
    /**
     * [imagecropper description]
     * @param  [type] $source_path   [description]
     * @param  [type] $target_width  [description]
     * @param  [type] $target_height [description]
     * @return [type]                [description]
     */
    public function  imagecropper($source_path, $target_path,$target_x, $target_y,$target_width, $target_height){
        $source_info = getimagesize($source_path);
        $source_width = $source_info[0];
        $source_height = $source_info[1];
        $source_mime = $source_info['mime'];
        $source_ratio = $source_height / $source_width;
        $target_ratio = $target_height / $target_width;
        // // 源图过高
        // if ($source_ratio > $target_ratio)
        // {
        //     $cropped_width = $source_width;
        //     $cropped_height = $source_width * $target_ratio;
        //     $source_x = 0;
        //     $source_y = ($source_height - $cropped_height) / 2;
        // }
        // // 源图过宽
        // elseif ($source_ratio < $target_ratio)
        // {
        //     $cropped_width = $source_height / $target_ratio;
        //     $cropped_height = $source_height;
        //     $source_x = ($source_width - $cropped_width) / 2;
        //     $source_y = 0;
        // }
        // // 源图适中
        // else
        // {
        //     $cropped_width = $source_width;
        //     $cropped_height = $source_height;
        //     $source_x = 0;
        //     $source_y = 0;
        // }
        $cropped_width = $target_width;
        $cropped_height = $target_height;
        $source_x = $target_x;
        $source_y = $target_y;
        switch ($source_mime)
        {
            case 'image/gif':
                return -1;
                $source_image = imagecreatefromgif($source_path);
                break;
            case 'image/jpeg':
            case 'image/jpg':
                $source_image = imagecreatefromjpeg($source_path);
                break;
            case 'image/png':
                $source_image = imagecreatefrompng($source_path);
                break;
            default:
                return false;
                break;
        }
        $target_image = imagecreatetruecolor($target_width, $target_height);
        $cropped_image = imagecreatetruecolor($cropped_width, $cropped_height);
        // 裁剪
        imagecopy($cropped_image, $source_image, 0, 0, $source_x, $source_y, $cropped_width, $cropped_height);
        // 缩放
        imagecopyresampled($target_image, $cropped_image, 0, 0, 0, 0, $target_width, $target_height, $cropped_width, $cropped_height);
        // $target_image = $source_image
        //保存图片到本地(两者选一)
        // $randNumber = mt_rand(00000, 99999). mt_rand(000, 999);
        // $fileName = substr(md5($randNumber), 8, 16) .".jpeg";
        imagejpeg($target_image,$target_path);
        imagedestroy($target_image);
        return 0;
        // //直接在浏览器输出图片(两者选一)
        // header('Content-Type: image/jpeg');
        // imagepng($target_image);
        // imagedestroy($target_image);
        // imagejpeg($target_image);
        // imagedestroy($source_image);
        // imagedestroy($target_image);
        // imagedestroy($cropped_image);
    }


    /**
     * [把文本，生成一个二维码，返回路径]
     * @param  [type] $text [description]
     * @return [type]       [description]
     */
    public function createQR($text){
        //1生成路径
        $datenow = date("Ymd");
        $path = $this->createpath($datenow);
        $filename = $this->createname();
        $filepath = $path .'/' .$filename;
        $qrdbpath = Config::get('common.url_root') . 'uploads/'.$datenow.'/'. $filename;
        //2、 生成二维码生成地址 for qrcode 存放一个地址  微信端浏览的
        trace("createQR:".$text);
        $this->createqrcode($text,$filepath);        
        return $qrdbpath;
    }

     /**
     * 生成二维码
     * @param $value  内容
     * @param int $matrixPointSize 图片大小
     * @param int errorCorrectionLevel 容错级别
     * @return string
     */
    private function createqrcode($value,$filepath){

        $nn = new \qrcode\phpqrcode();
        $nn->createqr($value,$filepath);

        //生成二维码图片
        $logo = FALSE;//准备好的logo图片
        $QR = $filepath;//已经生成的原始二维码图
        if ($logo !== FALSE) {
            $QR = imagecreatefromstring(file_get_contents($QR));
            $logo = imagecreatefromstring(file_get_contents($logo));
            $QR_width = imagesx($QR);//二维码图片宽度
            $QR_height = imagesy($QR);//二维码图片高度
            $logo_width = imagesx($logo);//logo图片宽度
            $logo_height = imagesy($logo);//logo图片高度
            $logo_qr_width = $QR_width / 5;
            $scale = $logo_width/$logo_qr_width;
            $logo_qr_height = $logo_height/$scale;
            $from_width = ($QR_width - $logo_qr_width) / 2;
            //重新组合图片并调整大小
            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,  $logo_qr_height, $logo_width, $logo_height);
        }
        //输出图片
        return true;
    }

    /**
     * [php 模拟http-get请求]
     * @return [type] [description]
     */
    public function http_get($url){
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
         
    }
  

    // public function get_client_ip($type = 0) {
    //     $type       =  $type ? 1 : 0;
    //     static $ip  =   NULL;
    //     trace("get_client_ip,sever:".json_encode($_SERVER));
    //     if ($ip !== NULL) return $ip[$type];
    //     if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    //         $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
    //         $pos    =   array_search('unknown',$arr);
    //         if(false !== $pos) unset($arr[$pos]);
    //         $ip     =   trim($arr[0]);
    //     }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
    //         $ip     =   $_SERVER['HTTP_CLIENT_IP'];
    //     }elseif (isset($_SERVER['REMOTE_ADDR'])) {
    //         $ip     =   $_SERVER['REMOTE_ADDR'];
    //     }
    //     // IP地址合法验证
    //     $long = sprintf("%u",ip2long($ip));
    //     $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    //     trace("get_client_ip,ip:".json_encode($ip));
    //     return $ip[$type];
    // }

    

    /**
     * [checkCaseRole description]
     * @param  [type] $roleId   [description]
     * @param  [type] $caseType [description]
     * @return [type]           [description]
     */
    public function checkCaseRole($roleId,$caseTypeArray){
        return 0;//权限放在页面
        // trace("checkCaseRole,$roleId,caseType:".json_encode($caseTypeArray));
        // $role = new \app\services\model\AdminRoles();
        // $roleInfo = $role->roleByRoleid($roleId);
        // if(!$roleInfo){                   
        //     return 2005;
        // }

        // $roleCase = Config::get('api')['roleCase'];
        // if(empty($roleInfo['role']) || empty($roleCase)){
        //     return 3002;
        // }
        // if(empty($roleCase[$roleInfo['role']])){
        //     return 3002;
        // }
        // // var_dump($roleInfo['role']);
        // $roleCaseName = $roleCase[$roleInfo['role']];
        // // var_dump($roleCaseName);exit;

        // if(!$roleCaseName){
        //     return 3002;   
        // }
        // if(in_array($roleCaseName, $caseTypeArray)){
        //     return 0;
        // }
        // else{
        //     return 3003;
        // }
    }

}